﻿using System;
using System.Collections;
using System.Xml;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

namespace InfoJetSoft.Service.Worker
{
	
	class XSNUpgradeBuildWorker
	{
		
		public static void  buildUpgrade(Manifest manifest)
		{
			XmlElement root = manifest.Doc.DocumentElement;
			string xsfPrefix = manifest.XsfPrefix;
			string upgradeName = NamespaceUtil.toFullName(xsfPrefix, "documentVersionUpgrade");

			Upgrade upgrade = new Upgrade();
			
			string useTransformFilter = upgradeName + "/" + NamespaceUtil.toFullName(xsfPrefix, "useTransform" );
			XmlElement useTransformElement = (XmlElement)DOMUtil.selectANode( root, useTransformFilter, manifest.NsResolver );
			if( useTransformElement != null )
			{
				string transform = useTransformElement.GetAttribute( "transform" );
				if( transform == null || transform.Trim().Length <= 0 )
				{
					return;
				}
				CABFile cabFile = CABFileFinder.lookupCABFile(manifest, transform);
				if (cabFile == null)
				{
					return;
				}
				XmlDocument upgradeDoc = DOMUtil.buildDoc(cabFile.ByteOutput);
				upgrade.Doc = upgradeDoc;
				upgrade.NsResolver = new NamespaceResolver(upgradeDoc);
				upgrade.XslPrefix = upgrade.NsResolver.GetPrefix(JetConstant.URI_XSL);
			}

			string useScriptFilter = upgradeName + "/" + NamespaceUtil.toFullName(xsfPrefix, "useScriptHandler" );
			XmlElement useScriptElement = (XmlElement)DOMUtil.selectANode( root, useScriptFilter, manifest.NsResolver );
			if( useScriptElement != null )
			{
				upgrade.UseScript = true;
			}

			if( useTransformElement == null && useScriptElement == null )
			{
				upgrade.DoNothing = true;
			}

			manifest.Upgrade = upgrade;
		}
	}
}